package model

import (
	"errors"
	"github.com/zhengchalei/gadmin/framework"
	"gorm.io/gorm"
)

func init() {
	framework.AutoMigrate("ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统用户'", &SysUser{})
	if framework.DB.Find(&SysUser{}).First(&SysUser{Model: framework.Model{ID: 1}}).RowsAffected == 0 {
		framework.DB.Save(&SysUser{
			Model:    framework.Model{ID: 1},
			Username: "super-admin",
			Password: "123456",
			Nickname: "超级管理员",
			DeptId:   1,
			Roles: []SysRole{
				{Model: framework.Model{ID: 1}},
				{Model: framework.Model{ID: 2}},
			},
		})
	}
	if framework.DB.Find(&SysUser{}).First(&SysUser{Model: framework.Model{ID: 2}}).RowsAffected == 0 {
		framework.DB.Save(&SysUser{
			Model:    framework.Model{ID: 2},
			Username: "admin",
			Password: "123456",
			Nickname: "管理员",
			DeptId:   1,
			Roles: []SysRole{
				{Model: framework.Model{ID: 1}},
				{Model: framework.Model{ID: 2}},
			},
		})
	}
}

type SysUser struct {
	framework.Model
	Username string `json:"username" form:"username" gorm:"not null;unique;comment:用户名;"`
	Nickname string `json:"nickname" form:"nickname" gorm:"not null;comment:昵称;"`
	Password string `json:"-" gorm:"not null;default:123456;comment:密码;"`
	// join
	Roles  []SysRole `json:"roles" gorm:"many2many:sys_user_role"`
	DeptId uint      `json:"deptId" form:"deptId" gorm:"not null;comment:所属部门;"`
	Dept   SysDept   `json:"dept"`
}

func (u *SysUser) BeforeDelete(tx *gorm.DB) (err error) {
	if u.Username == "super-admin" || u.Username == "admin" {
		return errors.New("管理员不允许删除")
	}
	return
}
